import _ from 'lodash';

export const parseQueryString = (url) => {
  let obj = {};
  let keyvalue = [];
  let key = '';
  let value = '';
  let rootUrl = url.substring(0, url.indexOf('?'));
  let paraString = url.substring(url.indexOf('?') + 1, url.length).split('&');
  for (let i in paraString) {
    keyvalue = paraString[i].split('=');
    key = keyvalue[0];
    value = keyvalue[1];
    obj[key] = decodeURIComponent(value);
  }
  obj.rootUrl = rootUrl;
  return obj;
}

export const updateState = (target, source) => {
  let newTarget = { ...target };
  for (let sKey in source) {
    if (source.hasOwnProperty(sKey)) {
      if (newTarget[sKey]) {
        if (newTarget.hasOwnProperty(sKey)) {
          if (_.isArray(source[sKey])&&_.isArray(newTarget[sKey])) {
            newTarget[sKey] = [].concat(source[sKey]);
          } else if (_.isFunction(source[sKey])&&_.isFunction(newTarget[sKey])) {
            newTarget[sKey] = source[sKey];
          } else if (_.isObject(source[sKey])&&_.isObject(newTarget[sKey])) {
            newTarget[sKey] = updateState(newTarget[sKey], source[sKey]);
          } else {
            newTarget[sKey] = source[sKey];
          }
        }
      } else {
        newTarget[sKey] = source[sKey];
      }
    }
  }
  return newTarget;
}